package com.alkin.thing.project.system.controller;

import com.alkin.thing.common.utils.SecurityUtils;
import com.alkin.thing.common.utils.StringUtils;
import com.alkin.thing.common.utils.file.FileUploadUtils;
import com.alkin.thing.common.utils.poi.ExcelUtil;
import com.alkin.thing.framework.aspectj.lang.annotation.Log;
import com.alkin.thing.framework.aspectj.lang.enums.BusinessType;
import com.alkin.thing.framework.config.ThingConfig;
import com.alkin.thing.framework.web.controller.BaseController;
import com.alkin.thing.framework.web.domain.AjaxResult;
import com.alkin.thing.framework.web.page.TableDataInfo;
import com.alkin.thing.project.system.domain.SysDictData;
import com.alkin.thing.project.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 数据字典信息
 * 
 * @author huangzy
 */
@RestController
@RequestMapping("/system/dict/data")
public class SysDictDataController extends BaseController
{
    @Autowired
    private ISysDictDataService dictDataService;

    @PreAuthorize("@ss.hasPermi('system:dict:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysDictData dictData)
    {
        startPage();
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        return getDataTable(list);
    }

    @Log(title = "字典数据", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:dict:export')")
    @GetMapping("/export")
    public AjaxResult export(SysDictData dictData)
    {
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        ExcelUtil<SysDictData> util = new ExcelUtil<SysDictData>(SysDictData.class);
        return util.exportExcel(list, "字典数据");
    }

    /**
     * 查询字典数据详细
     */
    @PreAuthorize("@ss.hasPermi('system:dict:query')")
    @GetMapping(value = "/{dictCode}")
    public AjaxResult getInfo(@PathVariable Long dictCode)
    {
        return AjaxResult.success(dictDataService.selectDictDataById(dictCode));
    }

    /**
     * 根据字典类型查询字典数据信息
     */
    @GetMapping(value = "/dictType/{dictType}")
    public AjaxResult dictType(@PathVariable String dictType)
    {
        return AjaxResult.success(dictDataService.selectDictDataByType(dictType));
    }

    /**
     * 新增字典类型
     */
    @PreAuthorize("@ss.hasPermi('system:dict:add')")
    @Log(title = "字典数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDictData dict)
    {
        dict.setCreateBy(SecurityUtils.getUsername());
        return toAjax(dictDataService.insertDictData(dict));
    }

    /**
     * 修改保存字典类型
     */
    @PreAuthorize("@ss.hasPermi('system:dict:edit')")
    @Log(title = "字典数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDictData dict)
    {
        dict.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(dictDataService.updateDictData(dict));
    }

    /**
     * 删除字典类型
     */
    @PreAuthorize("@ss.hasPermi('system:dict:remove')")
    @Log(title = "字典类型", businessType = BusinessType.DELETE)
    @DeleteMapping("/{dictCodes}")
    public AjaxResult remove(@PathVariable Long[] dictCodes)
    {
        return toAjax(dictDataService.deleteDictDataByIds(dictCodes));
    }


    /**
     * 新增字典类型
     */
    @Log(title = "字典数据", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult addRes(SysDictData dict, MultipartFile file)
    {

        String avatar = null;
        if (null != file) {
            try {
                //filePath = dictDataService.uploadFile(null,file);
                 avatar = FileUploadUtils.upload(ThingConfig.getAvatarPath(), file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            dict.setImgPath("/api"+avatar);
            //dict.setCreateBy(ContextUtils.getLoginUser().getUser().getUserName());
            return toAjax(dictDataService.insertDictData(dict));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(0);
    }

    /**
     * 修改保存字典类型
     */
    @Log(title = "字典数据", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult editRes(SysDictData sysDict, MultipartFile file)
    {

        if (file != null ){
            SysDictData dict = dictDataService.selectDictDataById(sysDict.getDictCode());
            if (null != dict){
                try {
                    //String filePath = dictDataService.uploadFile(dict, file);
                    String avatar = FileUploadUtils.upload(ThingConfig.getAvatarPath(), file);
                    sysDict.setImgPath("/api"+avatar);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            //sysDict.setUpdateBy(ContextUtils.getLoginUser().getUser().getUserName());
            return toAjax(dictDataService.updateDictData(sysDict));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(0);
    }

    /**
     * 删除字典类型
     */
    @PreAuthorize("@ss.hasPermi('system:dict:remove')")
    @Log(title = "字典类型", businessType = BusinessType.DELETE)
    @GetMapping("/delete/{dictCodes}")
    public AjaxResult removeRes(@PathVariable Long[] dictCodes)
    {
        return toAjax(dictDataService.deleteDictDataByIds(dictCodes));
    }

    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, SysDictData dict) {
        if (null == file || StringUtils.isEmpty(dict.getDictType())) {
            return toAjax(0);
        }

        return toAjax(dictDataService.importExcel(file, dict.getDictType()));
    }

    @GetMapping("/downloadExcel/downloadDict")
    public void downloadDictExcel(HttpServletResponse response, String type) {
        try {
            dictDataService.downloadExcel(response, type);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
